package com.school.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库清理工具
 * 用于直接执行SQL语句删除残留数据
 */
@Component
@Profile("cleanup")
public class DatabaseCleanup implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("开始清理残留数据...");
        
        // 打印所有学生用户
        System.out.println("当前学生用户列表：");
        jdbcTemplate.query(
            "SELECT id, username, name, student_id FROM user WHERE role = 'student'",
            (rs, rowNum) -> String.format(
                "ID: %d, 用户名: %s, 姓名: %s, 学号: %s",
                rs.getLong("id"),
                rs.getString("username"),
                rs.getString("name"),
                rs.getString("student_id")
            )
        ).forEach(System.out::println);
        
        // 删除指定的学生用户
        int deleted1 = jdbcTemplate.update("DELETE FROM user WHERE name = '学生1'");
        int deleted2 = jdbcTemplate.update("DELETE FROM user WHERE name = '学生2'");
        
        System.out.println("删除了 " + (deleted1 + deleted2) + " 条残留数据");
        
        // 再次打印所有学生用户，确认删除成功
        System.out.println("清理后学生用户列表：");
        jdbcTemplate.query(
            "SELECT id, username, name, student_id FROM user WHERE role = 'student'",
            (rs, rowNum) -> String.format(
                "ID: %d, 用户名: %s, 姓名: %s, 学号: %s",
                rs.getLong("id"),
                rs.getString("username"),
                rs.getString("name"),
                rs.getString("student_id")
            )
        ).forEach(System.out::println);
        
        System.out.println("数据清理完成");
    }
}
